const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const login = require('./routes/login');
const register = require('./routes/register');
const session = require("../help/session");
const fs = require("fs");

//模板引擎设置
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'hbs');

//设置layout
app.engine('.hbs', exphbs({
  partialsDir:'manager/views/public', //公共模板目录
  layoutsDir: 'manager/views/public/', //layout目录
  defaultLayout: 'layout',
  extname: '.hbs'
}));


//设置session
app.use(session);

//截获返回值
const jsonRes = express.response.json;

//格式化返回数据
app.use((req, res, next)=> {
    res.json = (obj) => {
      let wrapper = {
        code: 200,
        msg: "",
        data: obj
      }
      jsonRes.call(res, wrapper);
    };

    next();
  }
);

//不需要session的路由
app.use('/login', login);
app.use('/register', register);


//判断session是否存在（这以下的路由会判断session）
app.use((req, res, next) => {
  /*
  *登录状态
  */
  // if (req.session == null || req.session.username == null) 
  //   res.redirect("/manager/login");
  // else
    next();
})


//挂载routes下所有路由
let apiRoutesPath = path.join(__dirname,'/routes');
fs.readdirSync(apiRoutesPath).filter(file =>{
  return (file.indexOf(".") !== 0) && (file !== 'login.js') && (file !== 'register.js') && (file.slice(-3) == ".js");
}).forEach((fileName) =>{
  let routerName = path.basename(fileName,'.js')
  let routerPath = path.join(apiRoutesPath,routerName);
  let router = require(routerPath);
  app.use(`/${routerName}`, router);
})


//所有路由都未匹配到，直接到404
app.use(function (req, res, next) {
  res.render('public/404', {
    title: '404 NotFound',
    description: '你要访问的页面无法找到'
  });
});

module.exports = app;
